package sctu.edu.java.year2016.team01.xuhanmei.day20160610.ExerciseUDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2016/6/10.
 */
public class Weather extends Thread {
    String weather = "早上八点的天气预报，记得收听哦！";
    int port = 9898;//端口
    InetAddress inetAddress = null;
    MulticastSocket socket = null;//码头

    Weather() {//构造方法
        try {
            inetAddress = InetAddress.getByName("224.225.10.0");//实例化地址
            socket = new MulticastSocket(port);//实例化码头
            socket.setTimeToLive(1);//指定发送范围是本地网络,那如果是发送到外地网络该填入什么？
            socket.joinGroup(inetAddress);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void run() {
        while (true) {
            DatagramPacket packet;
            byte data[] = weather.getBytes();
            packet = new DatagramPacket(data, data.length, inetAddress, port);//声明集装箱
            System.out.println(new String(data));
            try {
                socket.send(packet);
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Weather w = new Weather();
        w.start();//创建本类对象
    }
}
